/**
 * 
 */
package edu.w106.platform.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @author w106
 *
 */
public class AccessFilter implements Filter {

    private final List<String> ipsList = new ArrayList<String>();

    @Override
    public void doFilter(ServletRequest request, ServletResponse resp, FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String cp = req.getContextPath();
        String cip = req.getRemoteAddr();

        try {
            check(cp, cip);
            chain.doFilter(request, resp);
        } catch (Exception e) {
            try {
                resp.setContentType("text/html;charset=UTF-8");
                ServletOutputStream sos = resp.getOutputStream();
                sos.write(e.getMessage().getBytes());
                sos.flush();
                sos.close();
                return;
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    }

    /**
     * ���ͻ���ip���Ƿ���context���õ�ip�б���.
     * @param context
     * @param clientIp
     * @throws Exception
     */
    private void check(String context, String clientIp) throws Exception {

        if (ipsList.contains(clientIp)) {
            return;
        } else {
            throw new Exception(String.format("Client(Ip:%s) visit %s Forbid.(Reason:Your IpAddress not in List) ",
                    clientIp, context));
        }

    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

    /**
     * @param accessIpList the accessIpList to set
     */
    public void addAccessIpList(String accessIp) {
        ipsList.add(accessIp);
    }

}
